<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('条款类型')" prop="type">
            <el-select v-model="form.type" filterable :placeholder="$t('条款类型')">
              <el-option
                v-for="dict in typeOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('提醒人')" prop="remindUserId">
            <UserSelect
              v-model="form.remindUserId"
              :multiple="true"
              fund-invest
              :placeholder="$t('提醒人')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('提醒状态')" prop="status">
            <el-switch
              v-model="form.status"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-text="$t('开启')"
              :inactive-text="$t('关闭')"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="form.status === 1" :span="12">
          <el-form-item :label="$t('提醒频率')" prop="reminderFrequency">
            <el-radio-group v-model="form.reminderFrequency">
              <el-radio
                v-for="dict in reminderFrequencyOptions"
                :key="dict.dictValue"
                :label="dict.dictValue"
              >{{ $t(dict.dictLabel) }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col v-if="form.status === 1" :span="12">
          <el-form-item
            :label="form.reminderFrequency === 'TIMER' ? $t('定时提醒时间') : $t('开始提醒时间')"
            prop="remindTime"
          >
            <el-date-picker
              v-model="form.remindTime"
              clearable
              style="width: 200px"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              format="yyyy-MM-dd HH:mm"
              :picker-options="pickerOptions"
              :placeholder="form.reminderFrequency === 'TIMER' ? $t('定时提醒时间') : $t('开始提醒时间')"
            />
          </el-form-item>
        </el-col>
        <el-col
          v-if="form.status === 1 && form.reminderFrequency === 'FREQUENCY' && !isEmpty(form.nextExecution)"
          :span="12"
        >
          <el-form-item :label="$t('下次执行时间')" prop="remindTime">
            <el-date-picker
              v-model="form.nextExecution"
              clearable
              style="width: 200px"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              format="yyyy-MM-dd HH:mm"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col v-if="form.reminderFrequency !== 'TIMER' && form.status === 1" :span="24">
          <el-form-item :label="$t('频率提醒表达式')" prop="cron">
            <Cron v-model="form.cron" :cron-value.sync="form.frequencyCronValue" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('关联合同')" prop="associatedContract">
            <el-select v-model="form.associatedContract" value="" :placeholder="$t('关联合同')" filterable clearable>
              <el-option
                v-for="dict in associatedContractDict"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('触发状态')" prop="isTrigger">
            <el-select v-model="form.isTrigger" value="" :placeholder="$t('触发状态')" filterable clearable>
              <el-option
                v-for="dict in isTriggerOption"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <div v-if="form.isTrigger === 'YCL' || form.isTrigger === 'WCL'">
          <el-col :span="12">
            <el-form-item :label="$t('触发时间')" prop="triggerTime">
              <DatePicker v-model="form.triggerTime" :placeholder="$t('触发时间')" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('应对措施')" prop="responseMethod">
              <el-input v-model="form.responseMethod" type="textarea" maxlength="2000" :placeholder="$t('应对措施')" />
            </el-form-item>
          </el-col>
        </div>
        <el-col :span="24">
          <el-form-item :label="$t('条款内容')" prop="remark">
            <el-input v-model="form.remark" type="textarea" maxlength="2000" :placeholder="$t('条款内容')" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('总结内容')" prop="summaryContent">
            <el-input v-model="form.summaryContent" type="textarea" maxlength="2000" :placeholder="$t('总结内容')" />
          </el-form-item>
        </el-col>
      </el-row>
      <FileTable
        :list.sync="form.fileList"
        :has-permi="hasPermi"
        data-type="deal_terms"
        :btn-show="!btnHide"
        :business-id="businessId"
      />
    </el-form>
    <div v-if="!btnHide" slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存，保存并启动流程，取消 三个按钮-->
      <SaveBtn :has-permi="hasPermi">
        <template v-slot:after>
          <el-button :has-permi="hasPermi" type="success" @click="submitForm('add')">
            {{ $t('保存并继续新增') }}
          </el-button>
        </template>
      </SaveBtn>
    </div>
  </div>
</template>

<script>
import { saveDealContractTerms, getDealContractTerms, actList } from '@/api/deal/terms/dealTerms'
import { getLpView } from '@/api/base/deal/dealBase.js'
import Cron from '@/components/Cron'

export default {
  components: {
    Cron
  },
  props: {
    hasPermi: {
      type: String,
      default: '',
      required: true
    }
  },
  data() {
    var checkTime = (rule, value, callback) => {
      if (!this.isEmpty(value) && this.isEmpty(this.form.id)) {
        console.log(value)
        if (!(value instanceof Date)) {
          value = new Date(value)
        }
        if (value.getTime() > new Date().getTime()) {
          callback()
        } else {
          callback(new Error(this.$t('不能早于当前时间')))
        }
      } else {
        callback()
      }
    }
    return {
      // 字典类型
      typeOptions: [],
      reminderFrequencyOptions: [],
      // 表单参数
      form: {
        fileList: []
      },
      businessId: this.$route.query.id,
      // 遮罩层
      loading: false,
      // 表单校验
      rules: {
        type: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        isTrigger: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        triggerTime: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        reminderFrequency: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        remindTime: [{ required: false, validator: checkTime, trigger: 'blur' }],
        remark: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
      },
      associatedContractDict: [],
      // 是否触发
      isTriggerOption: [],
      // 保存按钮隐藏
      btnHide: '',
      pickerOptions: {
        shortcuts: [{
          text: this.$t('5分钟后'),
          onClick(picker) {
            const start = new Date()
            start.setTime(start.getTime() + 60 * 1000 * 5)
            picker.$emit('pick', start)
          }
        }, {
          text: this.$t('10分钟后'),
          onClick(picker) {
            const start = new Date()
            start.setTime(start.getTime() + 60 * 1000 * 10)
            picker.$emit('pick', start)
          }
        }, {
          text: this.$t('30分钟后'),
          onClick(picker) {
            const start = new Date()
            start.setTime(start.getTime() + 60 * 1000 * 30)
            picker.$emit('pick', start)
          }
        }, {
          text: this.$t('明天'),
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() + 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: this.$t('7天后'),
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() + 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }, {
          text: this.$t('30天后'),
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() + 3600 * 1000 * 24 * 30)
            picker.$emit('pick', date)
          }
        }]
      }
    }
  },
  mounted() {
    this.$bus.$emit('async_done')
  },
  created() {
    this.getDicts('key_terms_status').then(response => {
      this.isTriggerOption = response.data
    })
    this.getDicts('reminder_frequency').then(response => {
      this.reminderFrequencyOptions = response.data
    })
    this.$bus.$emit('async_done')
  },
  methods: {
    // 初始化数据
    async init(data) {
      if (data !== null && data.id !== undefined) {
        this.loading = true
        await getDealContractTerms(data.id).then(response => {
          this.form = response.data
          if (this.form.type === null) {
            this.form.type = undefined
          }
          if (this.$route.query.id === null || this.$route.query.id === '' || this.$route.query.id === undefined) {
            this.businessId = this.form.dealId
          } else {
            this.businessId = this.$route.query.id
          }
          this.loading = false
        })
      } else {
        this.reset()
        this.loading = false
      }
      // 先从url里获取是那种项目, 获取不到在查表
      var dealType = this.$route.query.dealType
      if (!dealType) {
        debugger
        getLpView(this.form.dealId).then(response => {
          if (response.code === 200) {
            if (response.data && response.data[0]) {
              dealType = response.data[0].dealType
            }
          } else {
            this.msgError(this.$t(response.msg))
          }
          this.getDictDealType(dealType)
        })
      } else {
        this.getDictDealType(dealType)
      }
      this.initData(this.form)
    },
    async initData(data) {
      try {
        this.isSaveShow = data.isSaveShow
      } catch (e) {
        console.log('手动抓取异常:' + e)
      }
      // 合同下拉
      var dealIdTemp = this.businessId
      if (dealIdTemp === undefined || dealIdTemp === '' || dealIdTemp === null) {
        try {
          this.isSaveShow = data.isSaveShow
          dealIdTemp = data.formDealId
        } catch (e) {
          console.log('手动抓取异常:' + e)
        }
      }
      await actList(dealIdTemp).then(response => {
        this.associatedContractDict = response.data
      })
    },
    // 不同位置展示不同条款类型
    getDictDealType(dealType) {
      // 股权, 债权 条款类型
      if (dealType === 'bf') {
        this.getDicts('key_terms_type_bf').then(response => {
          this.typeOptions = response.data
        })
      } else {
        // 参股基金条款类型
        this.getDicts('key_terms_tyoe').then(response => {
          this.typeOptions = response.data
        })
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        dealId: this.$route.query.id,
        remindUserId: undefined,
        oaContractId: undefined,
        type: undefined,
        remindTime: undefined,
        associatedContract: undefined,
        isTrigger: undefined,
        triggerTime: undefined,
        responseMethod: undefined,
        remark: undefined,
        summaryContent: undefined,
        fileList: [],
        createBy: undefined,
        updateBy: undefined,
        createTime: undefined,
        updateTime: undefined,
        delFlag: undefined,
        reminderFrequency: 'TIMER',
        status: 1
      }
      this.resetForm('form')
    },
    // 取消按钮
    cancel() {
      this.reset()
      this.$parent.$parent.dealTermsOpen = false
      this.cancel2()
    },
    cancel2() {
      try {
        this.$parent.$parent.$parent.dealTermsOpen = false
      } catch (e) {
        console.log(e)
      }
    },
    // 关闭form页面
    closeForm() {
      // 关闭form页面遮罩层
      this.loading = false
      // 关闭form页面
      this.$parent.$parent.dealTermsOpen = false
      this.cancel2()
      // 刷新list页面
      try {
        this.$parent.$parent.getList()
      } catch (e) {
        this.$parent.$parent.$parent.getList()
      }
    },
    setRest() {
      this.form.responseMethod = undefined
      this.form.remark = undefined
      this.form.summaryContent = undefined
      this.form.createBy = undefined
      this.form.updateBy = undefined
      this.form.createTime = undefined
      this.form.updateTime = undefined
      this.form.delFlag = undefined
      // 关闭form页面遮罩层
      this.loading = false
      // 刷新list页面
      try {
        this.$parent.$parent.getList()
      } catch (e) {
        this.$parent.$parent.$parent.getList()
      }
    },
    /** 提交按钮 */
    submitForm: function(type) {
      this.$refs['form'].validate(valid => {
        if (valid) {
          var that = this
          if (that.form.parentId !== undefined && that.form.parentId !== null && that.form.parentId !== '') {
            var contractName = ''
            this.associatedContractDict.forEach(item => {
              if (this.form.associatedContract === item.dictValue) {
                contractName = ' (' + this.$t(item.dictLabel) + ') '
              }
            })
            that.$confirm(that.$t('该条款关联' + contractName + '合同,是否确认修改?'), that.$t('提示'), {
              confirmButtonText: that.$t('确定'),
              cancelButtonText: that.$t('取消'),
              type: 'warning'
            }).then(() => {
              that.saveSubmitForm(type)
            }).catch(() => {
              console.log('已取消!')
            })
          } else {
            that.saveSubmitForm(type)
          }
        } else {
          this.locationError(document)
        }
      })
    },
    saveSubmitForm(type) {
      if (this.form.triggerTime === '' || this.form.triggerTime === undefined || this.form.triggerTime === null) {
        this.form.triggerTime = null
      }
      this.loading = true
      if (!(this.form.remindUserId instanceof Array)) {
        this.$set(this.form, 'remindUserId', [])
      }
      if (this.form.remindUserId.length < 1) {
        this.form.remindUserIdStr = ''
      }
      this.loading = true
      // 新增/修改
      saveDealContractTerms(this.form).then(response => {
        if (response.code === 200) {
          this.msgSuccess(this.$t('保存成功'))
          if (type === 'add') {
            this.form.id = undefined
            this.form.parentId = undefined
            this.setRest()
          } else {
            this.closeForm()
          }
        } else {
          this.msgError(response.msg)
          this.loading = false
        }
      }).catch(() => {
        this.loading = false
      })
    }
  }
}
</script>
